﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using EtlComm;

namespace ETLHandler
{
    /// <summary>
    /// ETL执行引擎
    /// </summary>
    public class CETLHandler : IEtlInterface
    {
        private int _loadCount = 0;
        private int _extrCount = 0;

        #region IETLHandler 成员

        public IExtracter DataExtract { set; get; }
        public ILoader DataLoad { set; get; }
        public TaskObject Task { set; get; }
        public ILog log { set; get; }
        /// <summary>
        /// 加载记录数
        /// </summary>
        public int LoadCount
        {
            get { return _loadCount; }
        }
        /// <summary>
        /// 抽取记录数
        /// </summary>
        public int ExtrCount
        {
            get { return _extrCount; }
        }
        /// <summary>
        /// 执行任务
        /// </summary>
        /// <param name="StationID">加油站ID</param>
        /// <returns>执行结果，成功返回true</returns>
        /// 不会引发异常
        public bool Execute(string StationID)
        {
            DataExtract.ip = Task.SrcIP;
            DataExtract.TaskID = Task.TaskID;
            DataExtract.PrimaryKey = Task.PrimaryKeys[1];
            DataExtract.StationID = StationID;
            DataLoad.ip = Task.DstIP;
            DataLoad.Action = Task.Action;
           
            bool bRet = false;
            try
            {
                if (Task.HasParams)
                    Task.SQLStatement = string.Format(Task.Params[0], Task.ParamsStart, Task.ParamsEnd);
                using (DataTable srcTable = DataExtract.GetResult(Task.SQLStatement))
                {
                    _extrCount = srcTable.Rows.Count;
                    bRet = DataLoad.SetResult(srcTable);
                    _loadCount = (bRet == true) ? _extrCount : 0;
                }
                log.WriteLog(StationID, Task.TaskID.ToString(), 
                    string.Format("{0} 加油站{3} 任务{4} 抽取{1}条,加载{2}条。",DateTime.Now.ToString(),_extrCount,_loadCount,StationID,Task.TaskID));
            }
            catch (System.Exception ex)
            {
                log.WriteLog(StationID,Task.TaskID.ToString(),string.Format("执行引擎：\t{0} {1}\n",DateTime.Now.ToString(),ex.ToString()),LogType.ERROR);
                bRet = false;
            }
            catch
            {
                log.WriteLog(StationID, Task.TaskID.ToString(), "执行引擎：\t 未处理的异常...", LogType.ERROR);
                bRet = false;
            }

            return bRet;
        }

        #endregion
    }
}
